<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/15
 * 描述:
 */

namespace app\admin\controller;

use app\BaseController;
use app\result\admin\AdminResult;
use app\service\ChatWorkerService;
use think\App;
use think\facade\Route;

class BaseAdmin extends BaseController
{
    protected $admin_id = 0;
    protected $bs_oem_id = 0;
    protected $kefu_id = 10000;//客服id
    protected $admin;
    protected $unauthorized = [];//不需要鉴权验证的接口

    protected $notAuth = [];// 不需要登录(控制器+方法名称，小写),['login|login','help|list'];
    protected $param;
    protected $objResult = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->initialize();
    }

    protected function initialize()
    {
        $this->param = request()->filter('trim,htmlspecialchars')->param();

        $action = request()->action();
        $controller = strtolower(request()->controller());
        //bs_log(['url' => $url, 'controller' => $controller, 'action' => $action], 'info', 'admin_access_log.log');
        $authStr = strtolower($controller . '|' . $action);

        // 检查是否在免登录列表中
        $isNotAuth = false;
        if (is_array($this->notAuth)) {
            $isNotAuth = in_array($authStr, $this->notAuth);
        } else if (is_string($this->notAuth) && $this->notAuth === '*') {
            $isNotAuth = true;
        }

        // 如果需要登录验证
        if (!$isNotAuth) {
            $token = request()->header('Authorization');
            if (empty($token)) {
                //兼容特殊组件无法设置header，比如ueditor
                $token = input('Authorization', '', 'trim');
                if (!$token) {
                    data_return('登录过期', 401);
                }
            }

            // 验证token格式并清理
            if (stripos($token, 'Bearer ') === 0) {
                $token = trim(substr($token, 7)); // 移除 "Bearer " 前缀
            }

            if (empty($token)) {
                data_return('登录过期', 401);
            }

            $checkToken = (new AdminResult())->check_token($token, '*');
            if ($checkToken['code'] != 0) {
                data_return($checkToken['msg'], 401);
            }

            $admin = $checkToken['data'];
            if (!$admin) {
                data_return('登录过期', 401);
            } else {
                $this->admin = $admin;
                $this->admin_id = $admin['admin_id'];
                $this->bs_oem_id = $admin['bs_oem_id'];
                !defined('ADMIN_ID') && define('ADMIN_ID', $this->admin_id);
                !defined('BS_OEM_ID') && define('BS_OEM_ID', $this->bs_oem_id);
            }
        } else if ($token = request()->header('Authorization')) {
            // 如果提供了token，尝试解析但不强制要求成功
            if (stripos($token, 'Bearer ') === 0) {
                $token = trim(substr($token, 7)); // 移除 "Bearer " 前缀

                if (!empty($token)) {
                    $checkToken = (new AdminResult())->check_token($token, '*');
                    if ($checkToken['code'] == 0 && $checkToken['data']) {
                        $admin = $checkToken['data'];
                        $this->admin = $admin;
                        $this->admin_id = $admin['admin_id'];
                        $this->bs_oem_id = $admin['bs_oem_id'];
                        !defined('ADMIN_ID') && define('ADMIN_ID', $this->admin_id);
                        !defined('BS_OEM_ID') && define('BS_OEM_ID', $this->bs_oem_id);
                    }
                }
            }
        }


        // 权限检查只对需要验证的用户执行
        if (!empty($admin['role_id']) && $admin['role_id'] > 0) {
            //非超级管理员
            $url = request()->pathinfo();//路由
            if (!in_array($url, $this->unauthorized)) {
                $this->objResult = new AdminResult();
                if (stripos($url, '/') !== 0) {
                    $url = '/' . $url;
                }
                $checkAuth = $this->objResult->check_permission($admin['role_id'], $url);
                if (!$checkAuth) {
                    bs_log(['url' => $url, 'admin' => $admin], '无权', 'admin_access_log.log');
                    data_return('您没有权限访问', 403);
                }
            }
        }
        //bs_log(['url' => $url, 'admin' => $admin], 'info', 'admin_access_log.log');

        ChatWorkerService::init_gateway();
    }
}
